package com.watchmen.wechat.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.springframework.stereotype.Component;

/**
 * @author kk
 * @Description http请求工具
 */
@Component
public class HttpRequest {

	
	/**
	 * @param requestUrl 要请求的url
	 * @param requestMethod  请求方式
	 * @param outputStr  发送求的提交数据
	 * @return  返回请求结果
	 */
     public String doHttpsJson_HttpClient(String requestUrl, String requestMethod, String outputStr){
			
		try {
			//URL url = new URL(null,requestUrl,new com.sun.net.ssl.internal.www.protocol.https.Handler());
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
	        conn.setUseCaches(false);
	        // 设置请求方式（GET/POST）
	        conn.setRequestMethod(requestMethod);
	        conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	        // 当outputStr不为null时向输出流写数据
	        if (null != outputStr) {
	        	OutputStream outputStream = conn.getOutputStream();
	        	// 注意编码格式
	        	outputStream.write(outputStr.getBytes("UTF-8"));
	        	outputStream.close();
	        }
	        
	        
	        // 从输入流读取返回内容
	        InputStream inputStream = conn.getInputStream();            
	        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
	        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	        String str = null;
	        StringBuffer buffer = new StringBuffer();
	        while ((str = bufferedReader.readLine()) != null) {
	            buffer.append(str);
	        }
	        
	        
	        // 释放资源
	        bufferedReader.close();
	        inputStreamReader.close();
	        inputStream.close();
	        conn.disconnect();
	        return buffer.toString();
		} catch (MalformedURLException e) {
			System.out.println("连接超时：{}");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("https请求异常：{}");
			e.printStackTrace();
		}
		return "";
			
	}
}
